<template>
  <div class="item_detail">
    <van-swipe @change="onChange">
      <van-swipe-item
        v-for="(image, index) in goods.gallery"
        :key="index"
        style="position: relative"
      >
        <video-player
          v-if="playerOptions.sources[0].src && index == 0"
          ref="videoPlayer"
          width="100%"
          webkit-playsinline
          x5-playsinline
          x5-video-player-fullscreen="true"
          class="video-player vjs-custom-skin"
          style="object-fit: fill"
          :playsinline="playsinline"
          :options="playerOptions"
          @canplay="onPlayerCanplay($event)"
          @ended="onPlayerEnded($event)"
        >
        </video-player>
        <span
          v-if="playerOptions.sources[0].src && index == 0"
          @click="closePlayer"
          style="
            position: absolute;
            top: 10px;
            right: 10px;
            color: #fff;
            cursor: pointer;
          "
          >关闭</span
        >
        <!-- div解决image标签下面有4px溢出 -->
        <div
          v-else
          image
          :style="{ backgroundImage: `url(${image})` }"
          style="width: 100%; padding-bottom: 100%; background-size: 100% 100%"
        ></div>
      </van-swipe-item>
      <div class="custom-indicator" slot="indicator">
        {{ current + 1 }}/{{ gallerysize }}
      </div>
    </van-swipe>
    <p @click="$router.push({ path: '/items/pinsahre' })">团购</p>
    <van-cell-group class="item_cell_group">
      <van-cell class="item_info">
        <div>
          <!-- <div style="display: flex">
            <span class="item_price">{{
              (goods.retailPrice * 100) | yuan
            }}</span>
            <div class="cont5">
              <span>{{ (goods.discount * 100) | yuan }} 拼单价</span>
            </div>
          </div> -->
        </div>
        <div>
          活动结束时间：<span ref="countdown" style="color: red"
            >{{ day }}天{{ hour }}时{{ min }}分{{ second }}秒</span
          >
        </div>
        <div class="item-title">{{ goods.name }}</div>
        <div class="item_intro">{{ goods.brief }}</div>
      </van-cell>
    </van-cell-group>

    <!-- 拼团 -->
    <div
      style="background: #fff; margin-bottom: 14px"
      v-if="grouponList.length != 0"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          padding: 0 20px;
          border-bottom: 1px solid #f2f2f2;
        "
      >
        <p>这些人拼单成功，可参与拼单</p>
        <p @click="showl()">查看更多</p>
      </div>

      <ul>
        <li
          style="
            display: flex;
            text-align: center;
            justify-content: space-between;
            padding: 0 20px;
          "
          v-for="(item, index) in grouponList"
          :key="index"
        >
          <p
            style="
              height: 48px;
              display: flex;

              align-items: center;
              justify-content: center;
            "
          >
            <img
              :src="item.shareUrl"
              alt=""
              style="width: 35px; height: 35px; border-radius: 50%"
            />
            <span style="margin-left: 10px"> {{ item.userName }}</span>
          </p>
          <p
            style="
              margin: 0;
              display: flex;

              align-items: center;
              justify-content: center;
            "
          >
            <span ref="countdown" style="color: red"
              >{{ day }}天{{ hour }}时{{ min }}分{{ second }}秒</span
            >
          </p>
          <p
            @click="qupin(item.id)"
            style="
              padding-left: 13%;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            <span
              style="
                background: red;
                padding: 4px;
                border-radius: 4px;
                color: #fff;
              "
            >
              去拼单
            </span>
          </p>
        </li>
      </ul>
    </div>

    <div class="item_cell_group" style="margin-bottom: 0">
      <van-cell-group>
        <van-cell
          title="选择"
          isLink
          value="请选择商品规格"
          @click.native="skuClick(2)"
        />

        <van-cell title="运费" value="到付" />
      </van-cell-group>
    </div>

    <div
      style="
        width: 100%;
        height: 44px;
        line-height: 44px;
        text-align: center;
        display: flex;
        justify-content: center;
      "
    >
      <span
        style="
          height: 0px;
          border: 0.6px solid #d0d0d0;
          display: inline-block;
          margin: 21.7px 5px;
          width: 70px;
        "
      ></span>
      <span>详情</span>
      <span
        style="
          height: 0px;
          border: 0.6px solid #d0d0d0;
          display: inline-block;
          margin: 21.7px 5px;
          width: 70px;
        "
      ></span>
    </div>
    <div class="item_desc">
      <div class="item_desc_title">商品详情</div>
      <div
        class="item_desc_wrap"
        v-if="goods.detail"
        v-html="goods.detail"
      ></div>
      <div class="item_desc_wrap" v-else style="text-align: center">
        <p>无详情</p>
      </div>
    </div>
    <!-- 购买卡 -->

    <div
      v-show="showSku"
      style="
        width: 100%;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        position: fixed;
        bottom: 0;
        z-index: 1002;
        background: white;
      "
    >
      <div
        @click="sList()"
        v-if="!checkedAddress"
        style="
          width: 100%;
          background: white;
          height: 100px;
          text-align: center;
          margin-top: 10px;
          padding-top: 20px;
        "
      >
        <img :src="aress" alt="" width="30px" height="30px" />
        <p style="color: #8a8a8a">请选择收货地址</p>
      </div>
      <van-cell-group v-if="checkedAddress">
        <van-cell isLink @click="sList()" title="收货地址">
          <div slot="label">
            <div>
              <span>{{ adress.name }} </span>
              <span>{{ adress.tel }} </span>
            </div>
            <div>
              {{ adress.addressDetail }}
            </div>
          </div>
        </van-cell>
      </van-cell-group>
      <!-- 头部 -->
      <div
        style="display: flex; width: auto; margin-left: 20px; margin-top: 10px"
      >
        <img
          :src="logo"
          alt=""
          width="96px"
          height="96px"
          style="border-radius: 4px"
        />
        <div style="margin-left: 10px">
          <p
            style="color: #ff0000; font-size: 17px; margin: 0"
            v-if="shoptype == ''"
          >
            <span style="font-size: 15px">￥</span>
            <b>{{ queqian }}</b>
          </p>
          <p
            style="color: #ff0000; font-size: 17px; margin: 0"
            v-if="shoptype == 2"
          >
            <span style="font-size: 17px"
              >￥<b>{{ discount }} </b></span
            >
          </p>
          <p style="color: #b3b4b5; margin-bottom: 5px">
            库存 <span style=""> {{ queliang }}</span> 件
          </p>
          <p style="color: #b3b4b5; margin: 0">
            已选择 <span>{{ guiname }}</span>
          </p>
        </div>
      </div>
      <!-- 中间 -->
      <div>
        <ul>
          <li style="padding: 0 25px; font-size: 15px; padding-bottom: 10px">
            <div
              v-for="(item, inde) in guiarr"
              :key="inde"
              style="margin-top: 0; border-radius: 4px; padding: 3px"
            >
              <p>
                <span>{{ item.name }}</span>
              </p>

              <ul
                style="
                  display: flex;
                  flex-wrap: wrap;
                  justify-content: space-between;
                "
              >
                <li
                  v-for="(ement, index) in item.valueList"
                  :key="index"
                  ref="styab"
                  style="display: flex; padding: 6px; border-radius: 4px"
                  @click="chostab(ement, index, inde)"
                >
                  <img
                    :src="ement.picUrl ? ement.picUrl : logo_default"
                    alt=""
                    width="20px"
                    height="20px"
                    style="margin: 0 5px"
                  />
                  <p style="margin: 0; padding-right: 2px">
                    {{ ement.value }}
                  </p>
                </li>
              </ul>
            </div>
          </li>
        </ul>
      </div>
      <div
        style="
          display: flex;
          padding: 10px 21px;
          justify-content: space-between;
        "
      >
        <div><span>购买数量</span></div>
        <!-- 计数器 -->
        <div>
          <button
            type="button"
            class="deft"
            style="padding: 1px 7px"
            @click="defshu"
          ></button>
          <input
            type="tel"
            role="spinbutton"
            inputmode="numeric"
            aria-valuemax="1"
            readonly="readonly"
            aria-valuemin="1"
            aria-valuenow="1"
            class="stepper"
            v-model="qishu"
          />
          <button type="button" @click="addshu" class="addright"></button>
        </div>
      </div>

      <!-- 底部 -->
      <div
        style="display: flex; padding: 0 21px; justify-content: space-between"
      >
        <!-- <p
          style="width: 50%; text-align: center"
          class="tocard"
          @click="addCart()"
        >
          加入购物车
        </p> -->
        <p
          style="width: 100%; text-align: center; padding: 8.3px 0"
          class="buynowly"
          @click="buyGoods()"
        >
          立即购买
        </p>
      </div>
    </div>
    <div
      v-show="showSku"
      style="
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        position: fixed;
        top: 0;
        z-index: 1000;
      "
      @click="showSku = false"
    ></div>
    <!-- 底部按钮 -->
    <!-- <van-goods-action> -->

    <div
      style="
        display: flex;
        padding: 0 21px;
        justify-content: space-between;
        position: fixed;
        bottom: 0;
        width: 100%;
        background: #fff;
      "
    >
      <div
        style="margin-top: 6.5%; display: flex; flex-flow: column"
        role="button"
        tabindex="0"
        class="van-goods-action-icon"
        @click="addCollect"
      >
        <van-icon
          name="star"
          :color="goods.userHasCollect != 0 ? '#f7b444' : '#bebebe'"
          size="19"
        ></van-icon>
        <span style="margin-top: 5px; color: black">收藏</span>
      </div>
      <p
        style="width: 50%; text-align: center; padding: 5px 0"
        class="tocard"
        @click="skuClick('')"
      >
        <span
          ><span style="font-size: 18px">
            {{ (goods.retailPrice * 100) | yuan }}
          </span>
          <br />
          <span>单独购买</span></span
        >
      </p>
      <p
        style="width: 50%; text-align: center; padding: 5px 0"
        class="buynow"
        @click="skuClick(2)"
      >
        <span style="font-size: 18px">
          {{ (discount * 100) | yuan }}
        </span>
        <br />
        <span>拼单购买</span>
      </p>
    </div>
    <!-- <van-goods-action-button
        type="warning"
        @click="skuClick('')"
        text="单独购买"
      />
      <van-goods-action-button
        type="danger"
        @click="skuClick(2)"
        text="拼单购买"
      /> -->
    <!-- </van-goods-action> -->
    <!--popup 区域-->

    <div
      style="
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        background: #fff;
      "
      v-if="showlist"
    >
      <ul>
        <li
          @click="showlist = false"
          style="text-align: right; padding: 0 31px; padding-bottom: 9px"
        >
          关闭
        </li>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <li
            style="
              display: flex;
              text-align: center;
              justify-content: space-between;
              padding: 0 20px;
            "
            v-for="(item, index) in groupronList"
            :key="index"
          >
            <p
              style="
                margin: 0;
                height: 48px;
                display: flex;

                align-items: center;
                justify-content: center;
              "
            >
              <img
                :src="item.shareUrl"
                alt=""
                style="width: 35px; height: 35px; border-radius: 50%"
              />
              <span style="margin-left: 10px"> {{ item.userName }}</span>
            </p>
            <p
              style="
                margin: 0;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span ref="countdown" style="color: red"
                >{{ day }}天{{ hour }}时{{ min }}分{{ second }}秒</span
              >
            </p>
            <p
              @click="qupin(item.id)"
              style="
                margin: 0;
                padding-left: 13%;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span
                style="
                  background: red;
                  padding: 4px;
                  border-radius: 4px;
                  color: #fff;
                "
              >
                去拼单
              </span>
            </p>
          </li>
        </van-list>
      </ul>
    </div>
  </div>
</template>

<script>
import {
  cartGoodsCount,
  collectAddOrDelete,
  cartAdd,
  cartFastAdd,
  authInfo,
  updateDuration,
  purchaseDetails,
  adList,
  groupren,
  orderPrepay,
} from '@/api/api';

import {
  Sku,
  Swipe,
  SwipeItem,
  GoodsAction,
  GoodsActionButton,
  GoodsActionIcon,
  Popup,
  List,
  Toast,
  CouponList,
  CouponCell,
  Divider,
  Dialog,
} from 'vant';
import logo_default from '@/assets/images/logo.jpg';
import { getLocalStorage, setLocalStorage } from '@/utils/local-storage';
import popupProps from '../detail/popup-props';
import _ from 'lodash';

import $ from 'jquery';
import aress from '@/assets/images/aress.png';
import member_card_link from '@/assets/images/member_card_link.png';
import orgkai from '@/assets/images/kaiorg.jpg';
import member_card_head from '@/assets/images/member_card_head1.png';
export default {
  name: 'purchase',
  props: {
    itemId: [String, Number],
  },
  data() {
    const isLogin = !!localStorage.getItem('Authorization');
    return {
      img: {
        header: member_card_head,
      },
      aress,
      logo_default,
      guiarr: [],
      showlist: false,
      statu: '',
      cartInfo: 0,
      quegui: '',
      discount: '',
      loading: false,
      finished: false,
      queqian: '',
      shoptype: '',
      queliang: '',
      mosu: '',
      daindx: 0,
      guiname: '',
      logo: '',
      qishu: 1,
      vipid: null,
      isOpen: true,
      userId: -1,
      share_userId: -1,
      status: 1,
      myPlayer: undefined,
      isiOS: false,
      quota: 0,
      memberObj: {
        memberPrice: 0,
        price: 0,
        limitNum: 0,
      },
      userInfo: '',
      checkedAddress: true,
      showAddCar: true,
      current: 0,
      gallerysize: 1,
      ficationId: '',
      title: '',
      desc: '',
      addressId: '',
      specificationId: '',
      grouponList: '',
      link: '',
      orgkai: orgkai,
      initialSku: {},
      expireTime: '',
      imgUrl: '',
      page: 0,
      isLogin,
      xbutton: '<button style="position:absolute;top:0;right:0;">关闭</button>',
      share_icon: require('@/assets/images/share.png'),
      goods: '',
      groupronList: [],
      quanju: '',
      payWay: '0',
      skuGoods: {
        // 商品标题
        title: '',
        // 默认商品 sku 缩略图
        picture: '',
      },
      memberLevel: 0,
      oderId: '',
      cartInfo: 0,
      selectSku: {
        selectedNum: 0,
        selectedSkuComb: {
          sku_str: 'aa',
        },
      },
      day: '0',
      hour: '00',
      adress: '',
      min: '0',
      specificationId: '',
      second: '0',
      propsPopup: false,
      showSku: false,
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: true, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'video/mp4',
            src: '',
          },
        ],
        poster: '', //你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, //全屏按钮
        },
      },
      //定时器
      setTimeout: null,
      grouponId: '',
      member_card_link: member_card_link,
      show: false,
    };
  },
  // watch: {
  //   $route: 'initData',
  // },
  computed: {
    // playsinline() {
    //   let ua = navigator.userAgent.toLocaleLowerCase();
    //   let ua = navigator.userAgent.toLocaleLowerCase();
    //   // x5内核
    //   if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
    //     return false;
    //   } else {
    //     // ios端
    //     return true;
    //   }
    // },
  },

  watch: {
    $route(to, from) {
      if (
        this.$route.query.share_userId != null &&
        this.$route.query.share_userId != undefined &&
        this.$route.query.share_userId != ''
      ) {
        this.share_userId = this.$route.query.share_userId;
      } else {
        let { shareId } = getLocalStorage('shareId');
        this.share_userId = shareId;
      }
    },
  },

  created() {

    console.log(this.itemId,80943)
    if (
      this.$route.query.share_userId != null &&
      this.$route.query.share_userId != undefined &&
      this.$route.query.share_userId != ''
    ) {
      this.share_userId = this.$route.query.share_userId;
    } else {
      let { shareId } = getLocalStorage('shareId');
      this.share_userId = shareId;
    }
    this.initData();
    this.getUserInfo();
    this.isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  },

  beforeRouteLeave(to, from, next) {
    // 仅适用于本页面不作为H5着陆页的情况

    updateDuration({
      goodsId: this.goods.id,
      url: this.link,
    })
      .then((res) => {
        next();
      })
      .catch((err) => {
        next();
      });
  },

  methods: {
    showl() {
      this.showlist = true;
      document.title = '可参与的拼单';
    },

    // 去拼单

    qupin(id) {
      this.shoptype = 2;
      this.qishu = 1;
      this.grouponId = id;
      this.showSku = true;
      this.showlist = false;
    },

    onLoad() {
      if (this.page != 0 && this.groupronList.length < 10) {
        this.page = 0;
        this.groupronList = [];
      }

      this.page++;
      groupren({
        grouponId: Number(this.itemId),
        limit: 10,
        page: this.page,
      }).then((res) => {
        this.groupronList.push(...res.data.data.list);
        this.loading = false;
        this.finished = res.data.data.page >= res.data.data.pages;
      });
    },

    onChange(index) {
      this.current = index;
    },
    chostab(row, id, inde) {
      let vaarry = this.guiarr;
      vaarry[inde];
      vaarry.forEach((e, j) => {
        let a = id;
        let b = inde;
        let styab = this.$refs.styab;
        if (b == j) {
          e.valueList.forEach((e, i) => {
            if (a == i) {
              styab[i].className = 'zqan';
            } else {
              styab[i].className = 'fozan';
              styab[i].classList.remove('zqan');
            }
          });
        }
      });

      this.queqian = this.quegui[id].price;
      this.queliang = this.quegui[id].number;
      this.addid = this.quegui[id].id;
      this.discount = this.quegui[id].discount;
      this.specificationId = row.id;

      if (row.picUrl == undefined || row.picUrl == '') {
        this.logo = this.logo_default;
        return;
      }
      this.logo = row.picUrl;
    },
    // 计数器
    addshu(num) {
      if (this.shoptype == 2) {
        this.qishu = 1;
        Toast('拼团只能买一件');
        return;
      }
      if (this.qishu >= this.queliang) {
        Toast('数量已超出库存量！');
        return;
      }
      this.qishu = this.qishu + 1;
    },
    defshu() {
      if (this.qishu == 1) {
        Toast('商品数不能为零');
        return;
      }
      this.qishu = this.qishu - 1;
    },
    onPlayerCanplay(player) {
      //this.myPlayer = player;  //viedeoplayer不在<templelte>根<div>下  所以$refs获取不到子组件实例   播放时赋值   后期调用
      var ua = navigator.userAgent.toLocaleLowerCase();
      // x5内核
      if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        $('body')
          .find('video')
          .attr('x-webkit-airplay', true)
          .attr('x5-playsinline', true)
          .attr('webkit-playsinline', true);
      } else {
        // ios端
        $('body').find('video').attr('webkit-playsinline', 'true');
      }
    },

    onPlayerEnded(player) {
      if (!this.isiOS) {
        player.play();
        setTimeout(() => {
          player.pause();
        });
      }
    },

    closePlayer() {
      this.playerOptions.sources[0].src = '';
      this.playerOptions.sources[0].src = this.goods.videoUrl;
    },
    // 地址
    sList() {
      this.showSku = false;
      this.$router.push('/user/address');
    },
    skuClick(id) {
      this.shoptype = id;
      if (id == 2) {
        this.qishu = 1;
      }

      authInfo()
        .then((res) => {
          let status = res.data.data.status;
          if (status == 0) {
            Toast('请先验证手机号!');
            this.$router.push(`/check`);
            return;
          } else {
            this.showSku = true;
          }
        })
        .catch((err) => {});
    },
    initData() {
      purchaseDetails({
        grouponId: Number(this.itemId),
      })
        .then((res) => {
          setTimeout(() => {
            let styab = this.$refs.styab;
            styab.forEach((e, i) => {
              if (i == 0) {
                styab[i].className = 'zqan';
              } else {
                styab[i].className = 'fozan';
              }
            });
          }, 300);
          this.quanju = res.data.data;
          this.goods = res.data.data.litemallGoods;
          if (res.data.data.litemallAddress == undefined) {
            this.checkedAddress = false;
          } else {
            this.adress = res.data.data.litemallAddress;
            this.addressId = this.adress.id;
            this.checkedAddress = true;
          }

          this.expireTime = this.quanju.rules.expireTime;
          this.goodsId = this.goods.id;

          // 拼单人数
          this.grouponList = this.quanju.grouponList;
          this.gallerysize = this.goods.gallery.length;
          this.playerOptions.poster = this.goods.gallery[0];
          this.title = this.goods.name;
          this.desc = this.goods.brief;
          this.imgUrl = this.goods.gallery[0];
          // 默认pop第一个
          this.quegui = res.data.data.products;
          this.finspecition = res.data.data.specifications;
          // 默认pop第一个
          this.queqian = this.quegui[0].price;
          this.discount = this.quegui[0].discount;
          this.queliang = this.quegui[0].number;
          this.addid = this.quegui[0].id;
          this.mosu = this.quegui[0].value;
          this.specificationId = this.finspecition[0].valueList[0].id;

          res.data.data.specifications.forEach((item) => {
            this.guiarr.push(item);
            // 默认pop第一个
            this.guiname = this.guiarr[0].valueList[0].value;
            let logo = this.guiarr[0].valueList[0].picUrl;
            if (this.logo == '' || this.logo == null) {
              this.logo =
                this.goods.gallery[0] == null
                  ? logo_default
                  : this.goods.gallery[0];
            } else {
              this.logo = logo;

              this.specificationId = this.guiarr[0].valueList[0].id;
            }
          });

          if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
            this.expireTime = this.expireTime.replace(/\-/g, '/');
            this.countTime(this.expireTime);
          } else if (/(Android)/i.test(navigator.userAgent)) {
            this.countTime(this.expireTime);
          }
          // 链接
          this.link =
            process.env.VUE_APP_BASE_API +
            'wechat/static/html/redirect.html?app3Redirect=' +
            encodeURIComponent(window.location.href); // 分享链接
          let str = window.location.href,
            num = str.indexOf('#'); //取得整个地址栏
          this.link = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
          this.$wxShare({
            title: this.title,
            desc: this.desc,
            link: this.link,
            imgUrl: this.imgUrl,
          });
        })
        .catch((err) => {
          console.log(err, '错误运行');
        });
    },

    // 倒计时
    countTime(time) {
      let date = new Date();
      let now = date.getTime();
      let endDate = new Date(time);
      let end = endDate.getTime();
      let leftTime = end - now;
      if (leftTime >= 0) {
        // 天
        this.day = Math.floor(leftTime / 1000 / 60 / 60 / 24);
        // 时
        let h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
        this.hour = h < 10 ? '0' + h : h;
        // 分
        let m = Math.floor((leftTime / 1000 / 60) % 60);
        this.min = m < 10 ? '0' + m : m;
        // 秒
        let s = Math.floor((leftTime / 1000) % 60);
        this.second = s < 10 ? '0' + s : s;
      } else {
        this.day = 0;
        this.hour = '00';
        this.min = '00';
        this.second = '00';
      }
      // 等于0的时候不调用
      if (
        Number(this.hour) === 0 &&
        Number(this.day) === 0 &&
        Number(this.min) === 0 &&
        Number(this.second) === 0
      ) {
        return;
      } else {
        setTimeout((time) => {
          this.countTime(this.expireTime);
        }, 1000);
      }
    },
    // toCart() {
    //   this.$router.push({
    //     name: 'cart',
    //   });
    // },
    addCollect() {
      let type = this.goods.userHasCollect;
      if (type === 1) {
        type = 0;
      } else {
        type = 1;
      }

      collectAddOrDelete({
        valueId: this.itemId,
        type: type,
      }).then((res) => {
        if (this.goods.userHasCollect === 1) {
          this.goods.userHasCollect = 0;
        } else {
          this.goods.userHasCollect = 1;
          this.$toast({
            message: '收藏成功',
            duration: 1500,
          });
        }
      });
    },

    //添加购物车
    addCart(data) {
      //a 进行购物车中该种商品数量判定 超出数量限制回退 =>暂时先不做 因为该功能针对于会员  会员逻辑暂时没有做
      //b 进行商品数量判定 购物车中该商品数量(添加以后的数量)<=商品总数
      let that = this;
      let params = {
        goodsId: this.goodsId,
        number: this.qishu,
        groupId: this.grouponId,
        productId: this.addid,
        goodsId: this.goodsId,
        specificationId: this.specificationId,
        // price: data.selectedSkuComb.price / 100,
        // goodsSn: this.data.id,
        // goodsName: this.data.name,
        //specifications: this.getSpecifications(data.selectedSkuComb.s1),
        // sellAmout: data.selectedSkuComb.price / 100,
      };

      cartAdd(params)
        .then(() => {
          this.cartInfo = this.cartInfo + this.qishu;
          this.$toast({
            message: '已添加至购物车',
            duration: 1500,
          });
          that.showSku = false;
        })
        .then(() => {
          //重新获取购物车渲染数据
          this.getCartGoods();
        })
        .then(() => {});
    },
    //立即购买
    buyGoods(data) {
      //请求后端数据返回购物车号

      //立即购买
      if (!this.checkedAddress) {
        Dialog.confirm({
          title: '系统提示',
          message: '未检测到地址 \n是否添加？',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(() => {
            this.$router.push('/user/address');
            return;
          })
          .catch(() => {
            return;
          });
      }
      let para = {
        goodsId: this.goodsId,
        number: this.qishu,
        productId: this.addid,
        groupId: this.grouponId,
        castId: Number(this.itemId),

        type: this.shoptype,
        addressId: this.addressId,
        groupState: this.shoptype == 2 ? true : false,
        specificationId: this.specificationId,
        // price: data.selectedSkuComb.price / 100,
        // goodsSn: this.data.id,
        // goodsName: this.data.name,
        //specifications: this.getSpecifications(data.selectedSkuComb.s1),
        // sellAmout: data.selectedSkuComb.price / 100,
      };

      if (this.queliang == 0) {
        Toast('暂无库存！');
        return;
      }
      cartFastAdd(para).then((res) => {
        let rawCartId = res.data.data;

        setLocalStorage({
          CartId: rawCartId,
        });
        this.oderId = res.data.data;
        setLocalStorage({
          CartId: rawCartId,
        });
        // if (this.setTimeout) {
        //   window.clearTimeout(this.setTimeout);

        // if (this.setTimeout) {

        // }

        this.showSku = false;

        if (this.shoptype == 2) {
          this.pay();
        } else {
          setTimeout(() => {
            this.$router.push('/order/checkout');
          }, 1000);
        }
      });
    },

    // 获取用户会员信息
    async getUserInfo() {
      await authInfo().then((res) => {
        this.userInfo = res.data.data;
      });
    },

    pay() {
      if (this.payWay == '1') {
        let arr = new Array();
        arr.push(Number(this.oderId));
        // 对于货到付款，直接修改付款方式
        orderPrepay({
          orderIds: arr,
          payWay: 0,
          payType: 0,
        })
          .then((res) => {
            //console.log(JSON.stringify(res));
            this.$router.push({ path: '/order/payment/sucess' });
          })
          .catch((err) => {
            console.log(JSON.stringify(err.data.errmsg));
          });
        return;
      }
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            onBridgeReady,
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      } else {
        this.onBridgeReady();
      }
    },
    onBridgeReady() {
      let arr = new Array();
      arr.push(Number(this.oderId));
      orderPrepay({
        orderIds: arr,
        payWay: 0,
        payType: 0,
      })
        .then((res) => {
          const Mfbank = JSON.parse(res.data.data.wcPayData);

          let that = this;
          WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            {
              appId: Mfbank.appId, //公众号名称，由商户传入
              timeStamp: Mfbank.timeStamp, //时间戳，自1970年以来的秒数
              nonceStr: Mfbank.nonceStr, //随机串
              package: Mfbank.package,
              signType: Mfbank.signType, //微信签名方式：
              paySign: Mfbank.paySign, //微信签名
            },
            function (res) {
              if (res.err_msg == 'get_brand_wcpay_request:ok') {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                //判断是否是开通会员如果是将跳转到开通会员接口
                if (
                  that.goodsInfo &&
                  that.goodsInfo.goods_type == 1 &&
                  that.goodsInfo.name == '金牌会员年卡'
                ) {
                  //跳转到开通会员接口
                  // setMemberLevelOnline({ orderId: that.orderId }).then(res=>{
                  //   let status=res.data.data.member_status || 0
                  //   that.$router.push(
                  //     { name: 'paymentVipStatus', query: { status: status }}
                  //   );
                  // })
                  that.$router.push({
                    name: 'paymentVipStatus',
                    query: { status: 1 },
                  });
                } else {
                  that.$router.push({
                    name: 'paymentStatus',
                  });
                }
              }
            }
          );
        })
        .catch((err) => {});
    },
  },

  components: {
    [Popup.name]: Popup,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [Sku.name]: Sku,
    [List.name]: List,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [SwipeItem.name]: SwipeItem,
    [Sku.name]: Sku,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionButton.name]: GoodsActionButton,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [popupProps.name]: popupProps,
    [Divider.name]: Divider,
    [Dialog.Component.name]: Dialog.Component,
  },
};
</script>
<style lang="scss" scoped>
.fozan {
  background: #f7f8fa;
}
.zqan {
  color: #ee0a24;
  background: #fde7ea;
}

// 加号
.addright {
  position: relative;
  box-sizing: border-box;
  width: 28px;
  height: 28px;
  margin: 0;
  padding: 0;
  color: #323233;
  vertical-align: middle;
  background-color: #f2f3f5;
  border: 0;
  cursor: pointer;
}
.addright::before {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: currentColor;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  content: '';
  width: 50%;
  height: 1px;
}
.addright::after {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: currentColor;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  content: '';
  width: 1px;
  height: 50%;
}
// 计数器
.stepper {
  box-sizing: border-box;
  width: 32px;
  height: 28px;
  margin: 0 2px;
  padding: 0;
  color: #323233;
  font-size: 14px;
  line-height: normal;
  text-align: center;
  vertical-align: middle;
  background-color: #f2f3f5;
  border: 0;
  border-width: 1px 0;
  border-radius: 0;
  -webkit-appearance: none;
}
// 减号
.deft {
  position: relative;
  box-sizing: border-box;
  width: 28px;
  height: 28px;
  margin: 0;
  padding: 0;
  color: #323233;
  vertical-align: middle;
  background-color: #f2f3f5;
  border: 0;
  cursor: pointer;
}
.deft::before {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: currentColor;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  content: '';
  width: 50%;
  height: 1px;
}

// 购物车样式
.tocard {
  // padding: 10px 0;
  color: #fff;
  border-top-left-radius: 36px;
  border-bottom-left-radius: 36px;
  background-image: linear-gradient(to right, #ffca1e, #ff8a17);
}
.buynow {
  // padding: 10px 0;
  color: #fff;
  border-top-right-radius: 36px;
  border-bottom-right-radius: 36px;
  background-image: linear-gradient(to right, #ff5f34, #ef1125);
}
.buynowly {
  // padding: 10px 0;
  color: #fff;
  border-radius: 36px;

  background-image: linear-gradient(to right, #ff5f34, #ef1125);
}
/deep/.van-icon-star {
  padding-bottom: 4px;
}
/deep/.van-icon-cart {
  padding-bottom: 4px;
}
/deep/.van-info--dot {
  margin-top: 5px !important;
  margin-right: 5px !important;
}
// 底部按钮调整
// /deep/.van-goods-action-button--warning {
//   margin-left: 30px;
// }
.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  color: #fff;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}
/deep/.van-goods-action {
  border-top: 1px solid #eeeeee;
}
.cont5 {
  display: flex;
  align-items: center;
  margin-top: 1px;
  font-size: 16px;
  font-weight: bold;

  img {
    margin-left: 6px;
    width: 48px;
    height: 16px;
  }
}

/deep/ .van-cell__value {
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/ .vjs-custom-skin > .video-js .vjs-big-play-button {
  font-size: 2em;
  margin-top: 6.5em !important;
}

/deep/.vjs-fluid {
  padding-bottom: 43.75%;
}

/deep/.vjs-poster {
  background-size: 100% 100%;
}

/deep/.video-js .vjs-big-play-button .vjs-icon-placeholder:before,
.video-js .vjs-play-control .vjs-icon-placeholder:before,
.vjs-icon-play:before {
  font-size: 2.5em; //播放按钮三角大小
}

//播放按钮绝对定位
/deep/.vjs-custom-skin > .video-js .vjs-big-play-button {
  top: 10%;
  left: 52.5%;
  height: auto;
  line-height: auto;
}

/deep/.video-js .vjs-big-play-button {
  font-size: 20px;
  line-height: 3em !important;
  height: 3em !important;
  width: 3em;
  opacity: 0.6;
  border-radius: 1.5em;
  -webkit-transition: all 0.4s;
  transition: all 0.4s;
}

.item_detail {
  img {
    max-width: 100vw;
  }
}

.van-swipe-item::after {
  content: '';
}

.item_cell_group {
  margin-bottom: 15px;

  /deep/ .van-cell__title {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
  }

  /deep/ .van-cell__value {
    -webkit-box-flex: 6;
    -webkit-flex: 6;
    flex: 6;
    text-align: left;
  }
}

.item_price {
  font-size: 20px;
  color: $red;
  margin-right: 10px;
  font-weight: 600;
}

.item_market_price {
  color: $font-color-gray;
  text-decoration: line-through;
  font-size: $font-size-small;
}

.item-title {
  font-size: 16px;
  font-weight: bold;
  line-height: 1.6;
}

.item_dispatch {
  font-size: $font-size-small;
  color: $font-color-gray;
}

.item_intro {
  // line-height: 18px;
  // margin: 5px 0;
  line-height: 1.6;
  font-size: $font-size-small;
  color: $font-color-gray;
  overflow: hidden;
  display: -webkit-box;
  overflow-wrap: break-word;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.item_desc {
  background-color: #fff;

  /deep/ p {
    padding: 0 12px;
    margin-block-start: 0 !important;
    margin-block-end: 0 !important;
  }

  /deep/ img {
    width: 100%;
    display: block;
    margin-top: -1px;
  }
}

.item_desc_title {
  @include one-border;
  padding: 10px 0;
  text-align: center;
}

.van-info {
  right: 10px;
}

.subsequent {
  margin: -6px 0 6px 0;
}

.van-popup {
  border-radius: 16px 16px 0 0;
}
</style>
